<?php

namespace apiend\modules\attach\models;

use Yii;
use yii\db\Exception;
use common\models\shop\ShopAttachment;
use yii\helpers\ArrayHelper;
use common\helpers\Url;

/**
 * AlbumSearch represents the model behind the search form about [[\app\models\FanasocMemberApply]].
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class AlbumPictureUploadForm extends \common\base\Model {

    public $files = [];
    public $album_id;
    public $store_id = 0;
    private $_attachs = [];

    public function rules() {
        return [
            [['album_id', 'store_id'], 'integer'],
            [['files', 'album_id'], 'required'],
            [['files'], 'validateAttachs'],
        ];
    }

    /**
     * This validate Attachs attribute value.
     * @param string $attribute
     * @return mixed
     */
    public function validateAttachs($attribute) {
        if ($this->hasErrors()) {
            return;
        }
        $data = $this->$attribute;
        $attachs = [];
        foreach ($data as $attach) {
            $url = ArrayHelper::getValue($attach, 'url');
            $title = ArrayHelper::getValue($attach, 'title');
            $path = Url::relativePath($url);
            if (!$title) {
                $title = basename($path);
            }
            $attachs[] = [
                'size' => ArrayHelper::getValue($attach, 'size', 0),
                'width' => ArrayHelper::getValue($attach, 'width', 0),
                'height' => ArrayHelper::getValue($attach, 'height', 0),
                'title' => $title,
                'path' => $path,
                'channel_id' => ArrayHelper::getValue($attach, 'channel_id', 0),
            ];
        }
        if (empty($attachs)) {
            return $this->addError($attribute, '附件内容不能为空');
        }
        $this->_attachs = $attachs;
    }

    /**
     * Searching member apply
     * @param  array $params
     * @return \yii\data\ActiveDataProvider
     */
    public function save() {
        if (!$this->validate()) {
            return $this->dumpError();
        }
        $attachs = $this->_attachs;
        $model = new ShopAttachment();
        $model->store_id = intval($this->store_id);
        $model->group_id = $this->album_id;
        $model->admin_id = Yii::$app->user->id;
        $transaction = Yii::$app->db->beginTransaction();
        try {
            foreach ($attachs as $attach) {
                $_model = clone $model;
                $_model->setAttributes($attach);
                if (!$_model->save()) {
                    throw new Exception($_model->getErrorMsg());
                }
            }
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            $msg = $e->getMessage();
            Yii::error($msg);
            return false;
        }
        return true;
    }

}
